<template>
  <div class="app-container">
    <el-form inline>
      <!-- 表单元素 -->
      <el-form-item>
        <el-input v-model="searchContent" clearable placeholder="请输入内容" />
      </el-form-item>
      <!-- 查询与情况的按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getVideoList(1)"
          >查询</el-button
        >
      </el-form-item>
      <el-button type="primary" @click="showAddVideoDialog">添加视频</el-button>
    </el-form>
    <!-- table表格：展示用户信息的地方 -->
    <el-table border stripe v-loading="listLoading" :data="videoList">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="video_name" label="视频名称" width="200" />
      <el-table-column prop="order_id" label="序号" width="100" />
      <el-table-column prop="video_url" label="视频" width="100">
        <template slot-scope="{ row }">
          <img
            :src="require('@/assets/image/video.png')"
            alt="路线图"
            style="width: 80px; height: 80px"
            @click="routerGo(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="route_image_url" label="路线图" width="150">
        <template slot-scope="{ row }">
          <img
            :src="row.route_image_url || require('@/assets/image/mrtx.png')"
            alt="路线图"
            style="width: 80px; height: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间">
        <template slot-scope="{ row }">
          <div>{{ row.create_time?.replace("T", " ") }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230">
        <template slot-scope="{ row }">
          <HintButton
            type="primary"
            size="mini"
            icon="el-icon-edit"
            title="修改视频"
            @click="showAddVideoDialog(row)"
          />
          <el-popconfirm
            :title="`确定删除视频 ${row.video_name} 吗?`"
            @confirm="removeVideo(row.id)"
          >
            <HintButton
              style="margin-left: 10px"
              slot="reference"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              title="删除视频"
            />
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :current-page="current"
      :total="total"
      :page-size="count"
      :page-sizes="[4, 10, 20, 30, 40, 50]"
      style="padding: 20px 0"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @current-change="getVideoList"
      @size-change="handleSizeChange"
    />
    <!-- 对话框的结构 -->
    <el-dialog
      :title="addCourseFormTitle"
      :visible.sync="addVideoVisible"
      :before-close="addVideoCancel"
    >
      <el-form
        ref="addVideoForm"
        :model="addVideoForm"
        :rules="addVideoRules"
        label-width="120px"
      >
        <el-form-item label="视频名称：" prop="videoName">
          <el-input v-model="addVideoForm.videoName" />
        </el-form-item>
        <el-form-item label="视频上传：" prop="videoUrl">
          <el-upload
            class="upload"
            action=""
            :http-request="modeUpload"
            multiple
            :limit="1"
            :file-list="addVideoForm.videoUrl"
            :before-remove="beforeRemove"
            :before-upload="beforeAvatarUpload"
          >
            <el-button size="small" type="primary">{{
              videoUrlLoading ? "上传中..." : "上传视频"
            }}</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="路线图上传：" prop="routeImageUrl">
          <el-upload
            class="avatar-uploader"
            action=""
            :http-request="modeUpload2"
            :before-upload="beforeAvatarUpload2"
            :show-file-list="false"
          >
            <img
              v-if="addVideoForm.routeImageUrl"
              :src="addVideoForm.routeImageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="序号：" prop="orderId">
          <el-input v-model="addVideoForm.orderId" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addVideoCancel">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="addVideo"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  name: "videoList",
  data() {
    return {
      listLoading: false, // 是否显示列表加载的提示
      searchContent: "",
      searchFormFlag: false,
      importForm: [],
      current: 1, // 当前页码
      count: 4, // 每页数量
      total: 0, // 总数量
      dialogUserVisible: false, // 是否显示用户添加/修改的dialog
      showImport: false,
      currentUser: "",
      loading: false, // 是否正在提交请求中
      dialogRoleVisible: false, // 是否显示角色Dialog
      userRoleIds: [], // 用户的角色ID的列表
      isIndeterminate: false, // 是否是不确定的
      checkAll: false, // 是否全选
      mode: "",
      showPhoneInfo: false,
      modifyForm: {},
      Modifyid: "",
      // --------------
      // selectedOptions: [],
      courseId: "",
      addVideoVisible: false,
      videoList: [],
      addVideoForm: {
        videoName: "",
        videoUrl: [],
        routeImageUrl: "",
        orderId: "",
      }, // 当前要操作的user
      addVideoRules: {
        // 用户添加/修改表单的校验规则
        videoName: [
          { required: true, message: "视频名称不能为空", trigger: "blur" },
        ],
        videoUrl: [
          { required: true, message: "视频不能为空", trigger: "blur" },
        ],
        routeImageUrl: [
          { required: true, message: "路线图不能为空", trigger: "blur" },
        ],
        orderId: [{ required: true, message: "序号不能为空", trigger: "blur" }],
      },
      addCourseFormTitle: "",
      videoUrlLoading: false,
    };
  },

  //发请求一般情况下，我们都是在mounted去发，但是也可以在created内部去发
  created() {
    this.courseId = this.$route.query.courseId;
    this.getVideoList();
  },

  methods: {
    showAddVideoDialog(row) {
      this.addVideoVisible = true;
      console.log("showAddVideoDialog", row);
      if (row.id) {
        this.addCourseFormTitle = "修改视频";
        this.addVideoForm.videoName = row.video_name;
        let fileNameWithExtra = row.video_url.match(/\/([^/]+)$/)[1];
        let fileName = fileNameWithExtra.substring(
          fileNameWithExtra.indexOf("_") + 1
        );
        this.addVideoForm.videoUrl = [
          { name: fileName, uid: row.id, url: row.video_url },
        ];
        this.addVideoForm.routeImageUrl = row.route_image_url;
        this.addVideoForm.orderId = row.order_id;
        this.addVideoForm.id = row.id;
        console.log(111, this.addCourseForm);
      } else {
        this.addCourseFormTitle = "添加视频";
      }
    },
    addVideo() {
      this.$refs.addVideoForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          console.log("addVideo", this.addVideoForm);
          let params = JSON.parse(JSON.stringify(this.addVideoForm));
          params.videoUrl = params.videoUrl[0].url;
          params.videoCoursesId = this.courseId;
          console.log("params", params);
          const result = await this.$API.video.reqAddVideo(params);
          console.log("result", result);
          if (result.resultCode == 200) {
            this.$message.success("视频添加成功!");
            this.getVideoList(this.current);
            this.addVideoCancel();
          } else {
            this.$message.error("视频添加失败");
          }
          this.loading = false;
        } else {
          return;
        }
      });
    },
    addVideoCancel() {
      this.addVideoForm = {
        videoName: "",
        videoUrl: [],
        routeImageUrl: "",
        orderId: "",
      };
      this.$refs.addVideoForm.resetFields();
      this.addVideoVisible = false;
    },
    // 获取分页列表
    async getVideoList(pages = 1) {
      this.current = pages;
      const { current, count } = this;
      this.listLoading = true;
      const result = await this.$API.video
        .reqGetVideoList({
          current,
          count,
          videoCoursesId: this.courseId,
          condition: this.searchContent,
        })
        .catch(() => {
          this.listLoading = false;
          this.$message.error("获取列表失败");
        });
      console.log("getVideoList", result);
      if (result.resultCode == 200) {
        this.total = result.data.total;
        this.videoList = result.data.records;
      } else {
        this.$message.error(result.msg);
      }
      this.listLoading = false;
    },

    // 处理pageSize发生改变的监听回调
    handleSizeChange(pageSize) {
      this.count = pageSize;
      this.getVideoList();
    },

    //   根据输入进行搜索
    async search(pages) {
      if (this.searchContent.trim() == "") {
        this.searchContent = "";
        return;
      }
      console.log(typeof pages);
      if (typeof pages == "number") {
        console.log(pages);
        this.current = pages;
      } else {
        this.current = 1;
      }
      this.searchFormFlag = true;
      const { current, count } = this;
      this.listLoading = true;
      const condition = this.searchContent;
      const result = await this.$API.userList
        .reqSearchUser({ current, count, condition })
        .catch(() => {
          this.$message.error("获取列表失败");
        });
      this.listLoading = false;
      this.videoList = result.data.records.map((item) => {
        item.sex == "0" ? (item.sex = "男") : (item.sex = "女");
        item.status == "0" ? (item.status = "正常") : (item.status = "停用");
        switch (item.userType) {
          case "0":
            item.userType = "管理员";
            break;
          case "1":
            item.userType = "宿管";
            break;
          default:
            item.userType = "学生";
            break;
        }
        return item;
      });
      this.total = result.data.total;
    },
    // 清空搜索框内容清空
    resetForm() {
      if (this.searchContent == "") {
        if (this.searchFormFlag == true) {
          this.searchFormFlag = false;
          this.getVideoList();
        }
      }
    },
    // 清空按钮清空
    resetSearch() {
      if (this.searchFormFlag == true) {
        this.searchContent = "";
        this.searchFormFlag = false;
        this.getVideoList();
      } else {
        this.searchContent = "";
      }
    },
    async modeUpload(item) {
      console.log("modeUpload1", item);
      this.videoUrlLoading = true;
      const result = await this.$API.course.reqUploadImage({
        file: item.file,
      });
      if (result.resultCode == 200) {
        console.log("modeUpload", result, result.data);
        item.file.url = result.data;
        this.addVideoForm.videoUrl.push(item.file);
        this.videoUrlLoading = false;
        console.log("modeUpload2", this.addVideoForm);
        this.$message({
          message: "视频上传成功",
          type: "success",
        });
      } else {
        this.$message.error("视频上传失败");
      }
    },
    async modeUpload2(item) {
      console.log("modeUpload2", item);
      const result = await this.$API.course.reqUploadImage({
        file: item.file,
      });
      if (result.resultCode == 200) {
        console.log("modeUpload", result);
        this.addVideoForm.routeImageUrl = result.data;
        this.$message({
          message: "路线图上传成功",
          type: "success",
        });
      } else {
        this.$message.error("路线图上传失败");
      }
    },
    beforeAvatarUpload(file) {
      const isVideo = file.type.startsWith("video/");
      console.log("isVideo", isVideo);
      if (!isVideo) {
        this.$message.error("只能上传视频!");
      }
      return isVideo;
    },
    beforeAvatarUpload2(file) {
      const isImage = file.type.startsWith("image/");
      // const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error("只能上传图片!");
      }
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      return isImage;
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${file.name}?`);
      console.log("beforeRemove", file, fileList, this.addVideoForm);
      this.addVideoForm.videoUrl.splice(0, 1);
      return true;
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    // beforeUploadFile(file) {
    //   let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
    //   let size = file.size / 1024 / 1024;
    //   if (extension !== "xlsx") {
    //     this.$message.warning("只能上传后缀是.xlsx的文件");
    //   }
    //   if (size > 10) {
    //     this.$message.warning("文件大小不得超过10M");
    //   }
    // },

    // 删除视频
    async removeVideo(id) {
      const result = await this.$API.video.reqdeleteVideo({ id });
      if (result.resultCode == 200) {
        this.$message.success("删除成功!");
        this.getVideoList(
          this.videoList.length === 1 ? this.current - 1 : this.current
        );
      } else {
        this.$message.error("删除失败");
      }
    },
    routerGo(row) {
      console.log("routerGo", row);
      this.$router.push({
        path: "/video/player",
        query: { url: row.video_url },
      });
    },
  },
  computed: {
    userName() {
      return this.$store.state.userInfo.userName || getToken("userName");
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.Import {
  .item {
    margin-bottom: 5px;
    height: 44px;
    display: flex;
    align-items: center;

    .ImportSpan {
      font-size: 16px;
    }

    .uploadBtn {
      display: inline-block;
      width: 88px;
      height: 40px;
    }
  }

  // .download{

  // }
}

/deep/.el-upload-dragger {
  display: inline-block;
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 4px;
}
.app-container {
  position: relative;
}
.video-box {
  width: 50%;
  position: absolute;
  top: 300px;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
}

/deep/.video-js .vjs-big-play-button {
  width: 88px !important;
  height: 88px !important;
  border-radius: 50% !important;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border: 0;
  font-size: 56px;
  object-fit: cover;
}

/deep/ .vjs-error .vjs-error-display::before {
  display: none;
}

// /deep/ .vjs-modal-dialog-content {
//   display: none;
// }

// /deep/.video-js .vjs-control-bar {
//   height: 58px;
//   line-height: 58px;
//   background: rgba(0, 0, 0, 0.24) !important;
//   // background: #ac8282;
// }

// /deep/.vjs-button>.vjs-icon-placeholder:before {
//   font-size: 40px;
// }

// /deep/.video-js .vjs-control {
//   font-size: 22px;
//   line-height: 58px;
// }

// /deep/.vjs-playback-rate .vjs-playback-rate-value {
//   line-height: 58px;
// }

// /deep/.vjs-button>.vjs-icon-placeholder:before {
//   line-height: 60px;
// }

// /deep/.vjs-remaining-time-display {
//   font-size: 24px;
// }

// /deep/.video-js .vjs-big-play-button {
//   background-color: rgba(0, 0, 0, 0.5);
// }

// /deep/.video-js .vjs-slider {
//   background-color: rgba(255, 255, 255, 0.5);
// }

// // 视频封面
// /deep/.video-js .vjs-poster {
//   background-size: cover !important;
// }
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
